package com.jxpanda.spring.module.auth.endpoint;

import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import java.util.Map;


@Slf4j
@RestController(JwkSetEndpoint.BEAN_NAME)
@RequestMapping
@ConditionalOnProperty(prefix = "panda.spring.auth", name = {"endpoint.enable-jwk-set", "token.jwt.enable"}, havingValue = "true")
public class JwkSetEndpoint {

    public static final String BEAN_NAME = "jwkSetEndpoint";

    public static final String DEFAULT_PATH = "/.well-known/jwks.json";

    private final JWKSet jwkSet;

    public JwkSetEndpoint(JWKSource<SecurityContext> jwkSource) {
        ImmutableJWKSet<SecurityContext> immutableJWKSet = (ImmutableJWKSet<SecurityContext>) jwkSource;
        this.jwkSet = immutableJWKSet.getJWKSet();
    }

    @PostConstruct
    private void init() {
        tryPrintLog();
    }

    @GetMapping("${panda.spring.auth.endpoint.jwk-set:" + DEFAULT_PATH + "}")
    public Mono<Map<String, Object>> jwkSet() {
        return Mono.just(jwkSet.toJSONObject(true))
                .doOnSuccess(json -> tryPrintLog());
    }

    private void tryPrintLog() {
        if (log.isDebugEnabled()) {
            log.debug("[PANDA SPRING AUTH]JWKSet 已返回，完整值为: {}", jwkSet.toJSONObject(false));
        }
    }

}
